﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using ARR.UI.Commands;
using System.Collections.ObjectModel;
using ARR.UI.Models;
using ARR.Shared;
using ARR.Entities;
using System.ComponentModel;
using System.Windows.Data;
using ARR.UI.ArticlesService;
using System.Windows;
using ARR.UI.Views;
using System.ServiceModel;

namespace ARR.UI.ViewModels
{
    public class SalesMasterViewModel : WorkspaceViewModel
    {
        private ISalesMasterModel model;
        private ICommand deleteCommand;
        private ICommand saveCommand;
        private ICommand selectionChangedCommand;
        private ICommand rowValidatingCommand;
        private ICommand runValidationsCommand;
        private ICommand theoreticalMarginsCommand;
        private ICommand filterByCategoryCommand;


        public SalesMasterViewModel(ISalesMasterModel model)
        {
            this.model = model;
            this.DisplayName = Labels.MaestroDeVentas;
            
            this.SelectedCategory = model.Categories.First();
            FilterByCategory();
        }


        public ICommand FilterByCategoryCommand
        {
            get
            {
                if (filterByCategoryCommand == null)
                {
                    filterByCategoryCommand = new RelayCommand(param => FilterByCategory(), c => !IsClosing);
                }
                return filterByCategoryCommand;
            }
        }

        public ICommand DeleteCommand
        {
            get
            {
                if (deleteCommand == null)
                {
                    deleteCommand = new RelayCommand(param => DeleteSales());
                }
                return deleteCommand;
            }
        }

        public ICommand SaveCommand
        {
            get
            {
                if (saveCommand == null)
                {
                    saveCommand = new RelayCommand(
                        param => SaveSales());
                }
                return saveCommand;
            }
        }

        public ICommand RunValidationsCommand
        {
            get
            {
                if (runValidationsCommand == null)
                {
                    runValidationsCommand = new RelayCommand(param => RunValidations());
                }
                return runValidationsCommand;
            }
        }

        public Visibility IsVisibleResultsGV 
        {
            get
            {
                return Results.Any() ? Visibility.Visible : Visibility.Collapsed;
            }
        }


        
        public bool IsBusy { get; set; }

        public ObservableCollection<ArticleSale> Sales
        {
            get
            {
                return model.Sales;
            }
        }

        public ObservableCollection<ImporterResult> Results
        {
            get
            {
                return new ObservableCollection<ImporterResult>(model.Results);
            }
        }
        
        public ObservableCollection<Category> Categories
        {
            get
            {
                return new ObservableCollection<Category>(model.Categories);
            }
        }

        public ICollectionView SalesCollection
        {
            get
            {
                CollectionViewSource source = new CollectionViewSource();
                source.CollectionViewType = typeof(ArticleSale);
                source.Source = model.Sales;

                return source.View;
            }
        }

        public Category SelectedCategory { get; set; }

        public ICommand TheoreticalMarginsCommand
        {
            get
            {
                if (theoreticalMarginsCommand == null)
                {
                    theoreticalMarginsCommand = new RelayCommand(param => OpenTheoreticalMarginsPopup());
                }
                return theoreticalMarginsCommand;
            }
        }



        public void FilterByCategory()
        {
            if (SelectedCategory != null)
            {
                LoadSales();
            }
        }

        private void DeleteSales()
        {

        }

        private void SaveSales()
        {
            if (AreValid())
            {
                model.Save();

                OnPropertyChanged<SalesMasterViewModel>(vm => vm.Sales);
            }
        }

        private bool AreValid()
        {
            foreach (ArticleSale sale in Sales)
            {
                if (!sale.IsValid)
                    return false;
            }

            return true;
        }

        private void LoadSales()
        {
            IsBusy = true;

            ArticlesServiceClient service = new ArticlesServiceClient();
            service.GetAllSalesCompleted += new EventHandler<GetAllSalesCompletedEventArgs>(service_GetAllSalesCompleted);
            service.GetAllSalesAsync(WorkspaceData.Instance.RangeReview.Id, SelectedCategory.Id);

            OnPropertyChanged<SalesMasterViewModel>(vm => vm.IsBusy);
        }
        
        private void OpenTheoreticalMarginsPopup()
        {
            var selecteds = this.model.Results.Where(x => x.IsSelected).Select(x => x.ItemId).Distinct();

            if (!selecteds.Any())
            {
                (new Alert(Messages.MargenTeoricoCategoriasSeleccionados, Labels.Advertencia, AlertType.Warning)).ShowDialog();
            }
            else
            {
                TheoreticalMarginsViewModel vm = new TheoreticalMarginsViewModel(selecteds, true);
                TheoreticalMarginsPopupView popup = new TheoreticalMarginsPopupView();
                popup.DataContext = vm;


                bool? result = popup.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    RunValidations();
                }
            }
        }

        private void RunValidations()
        {
            model.RunSalesValidations();

            OnPropertyChanged<SalesMasterViewModel>(p => p.Results);
            OnPropertyChanged<SalesMasterViewModel>(p => p.IsVisibleResultsGV);
        }

        void service_GetAllSalesCompleted(object sender, GetAllSalesCompletedEventArgs e)
        {
            IsBusy = false;
            OnPropertyChanged<SalesMasterViewModel>(vm => vm.IsBusy);

            if (e.Error == null)
            {
                (sender as ICommunicationObject).Close();
                model.Sales = new ObservableCollection<ArticleSale>(e.Result);
                OnPropertyChanged<SalesMasterViewModel>(vm => vm.Sales);
            }
            else
            {
                (sender as ICommunicationObject).Abort();
                throw e.Error;
            }
            
        }


    }
}
